$(function () {
    initArtList()
    let indexAdd = null
    let indexEdit = null
    $('#btnAddCate').on('click', function () {
        indexAdd = layui.layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '添加文章分类',
            content: $("#dialog-add").html()
        })
    })
    // 添加分类
    $('body').on('submit', '#form-add', function (e) {
        e.preventDefault();
        $.ajax({
            method: 'POST',
            url: '/my/article/addcates',
            data: $(this).serialize(),
            success(res) {
                if (res.status !== 0) return layui.layer.msg('添加图书分类失败!')
                initArtList()
                layui.layer.msg(res.message)
                layui.layer.close(indexAdd)
            }
        })
    })

    // 修改分类
    $('tbody').on('click', '.btn-edit', function () {
        indexEdit = layui.layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '修改文章分类',
            content: $("#dialog-edit").html()
        })

        let id = $(this).attr('data-id');
        $.ajax({
            url: '/my/article/cates/' + id,
            success(res) {
                layui.form.val('form-edit', res.data)
            }
        })
    })

    $('body').on('submit', '#form-edit', function (e) {
        e.preventDefault();
        $.ajax({
            method: 'POST',
            url: '/my/article/updatecate',
            data: $(this).serialize(),
            success(res) {
                if (res.status !== 0) return layui.layer.msg('更新图书分类失败!')
                initArtList()
                layui.layer.msg(res.message)
                layui.layer.close(indexEdit)
            }
        })
    })

    // 删除分类
    $("tbody").on("click", '.btn-delete', function () {
        let id = $(this).attr('data-id')
        layui.layer.confirm('确认删除?', { icon: 3, title: '提示' }, function (index) {
            $.ajax({
                url: '/my/article/deletecate/' + id,
                success(res) {
                    if (res.status !== 0) return layui.layer.msg('删除分类失败!')
                    initArtList()
                    layui.layer.msg(res.message)
                    layui.layer.close(index)
                }
            })
        })

    })

})


function initArtList() {
    $.ajax({
        url: '/my/article/cates',
        success(res) {
            if (res.status != 0) return layui.layer.alert(res.message)
            let htmlStr = template('tpl-table', res)
            $('tbody').html(htmlStr)
        }
    })
}

